package my.soft.aiteacher.teacher.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import my.soft.aiteacher.common.mapper.UserMapper;
import my.soft.aiteacher.common.pojo.UserDo;
import my.soft.aiteacher.exception.BusinessException;
import my.soft.aiteacher.teacher.mapStruct.ChapterMapStruct;
import my.soft.aiteacher.teacher.mapper.ChapterMapper;
import my.soft.aiteacher.teacher.mapper.FileUploadMapper;
import my.soft.aiteacher.teacher.pojo.ChapterDo;
import my.soft.aiteacher.teacher.pojo.ChapterVo;
import my.soft.aiteacher.teacher.pojo.FileUpload;
import my.soft.aiteacher.teacher.service.IChaptersService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, ChapterDo> implements IChaptersService {
    @Value("${file.upload-dir}")
    private String uploadPath;
    @Resource
    private FileUploadMapper fileUploadMapper;
    @Resource
    private ChapterMapper chapterMapper;
    @Resource
    private ChapterMapStruct chapterMapStruct;

    @Override
    @Transactional
    public List<ChapterVo> submitChapters(List<ChapterVo> chapters) {
        List<ChapterDo> finalChapterDoList = new ArrayList<>();
        Long id = chapters.get(0).getFileId();
        List<ChapterDo> chapterDoList = chapterMapper.selectList(new QueryWrapper<ChapterDo>().eq("file_id", id));
        if(Objects.nonNull(chapterDoList)){
            chapterMapper.delete(new QueryWrapper<ChapterDo>().eq("file_id", id));
            //删除服务器中存在的文件
            for (ChapterDo chapter : chapterDoList) {
                File file = new File(chapter.getImgSrc());
                if(file.exists()){
                    file.delete();
                }
            }
        }
        List<ChapterVo> chapterVoList = new ArrayList<>();
        Process process = null;
        for (ChapterVo chapter : chapters) {

            Long fileId = chapter.getFileId();
            FileUpload fileUpload = fileUploadMapper.selectById(fileId);
            String filePath = fileUpload.getVideoPath();
            //从liunx中获取file
            File file = new File(filePath);
            if(!file.exists()){
                throw new BusinessException("文件不存在,无法获取封面，请联系管理员");
            }
            //将filePath去掉最后的文件名
            String path = filePath.substring(0, filePath.lastIndexOf("/"));
            String coverPath = path + "/chapters"+chapter.getStartTime()+"cover.jpg";
            //利用ffmpeg根据传入的时间截取视频封面
            try{
                File cover = new File(coverPath);
                if(cover.exists()){
                    cover.delete();
                }
                String[] command = {
                        "/usr/bin/ffmpeg",
                        "-i", filePath,
                        "-ss", chapter.getStartTime(),
                        "-vframes", "1",
                        coverPath
                };
                process = Runtime.getRuntime().exec(command);
                int code = process.waitFor();
                if(code != 0){
                   throw new BusinessException("截取封面失败,请联系管理员");
                }
            }catch (Exception e){
                e.printStackTrace();
                throw new BusinessException("截取封面失败,请联系管理员");
            } finally {
                if(process!=null){
                    process.destroy();
                }
            }
            chapter.setImgSrc(coverPath);
            chapterVoList.add(chapter);
            finalChapterDoList.add(chapterMapStruct.voToDo(chapter));
        }
        chapterMapper.insert(finalChapterDoList);
        return chapterVoList;
    }

    @Override
    public List<ChapterDo> chapterList(Long fileId) {
        FileUpload fileUpload = fileUploadMapper.selectById(fileId);
        if(Objects.isNull(fileUpload)){
            throw new BusinessException("文件不存在,无法获取章节，请联系管理员");
        }
        return chapterMapper.selectList(new QueryWrapper<ChapterDo>().eq("file_id", fileId));
    }
}
